Factory Pattern
Factory patterns are widely used in Software Development. There are three type of factory patterns. They are Simple Factory Pattern, Factory Pattern, Abstract Factory Pattern. We will introduce these three pattern.
Simple Factory Pattern
There is only a factory class which used to create simple object.
Scenario: The objects needed to create is simple and not too much.
Example: we have many fruits to get. Those fruits have the same interface.
1 | public interface Fruit{} |
Then we have a factory to get fruits.
1 | public class FruitFactory { |
Now we could use this factory like this.
1 | FruitFactory factory = new FruitFactory(); |
Just according to different parameters we could get different fruit objects.
Factory Pattern
This pattern would be more complex. We need to abstract the factory and implement different factory for different objects.
Scenario: This pattern could be used when we don’t need to know or care about each type of object which would created by factory.
Now we want to implement a hiring class that could find different kind of worker to do the job.
First we have a worker interface and several kind of worker class
1 | public interface Worker { |
Then we could implement a abstract factory class and each worker should have a factory class.
1 | public interface WorkerFactory { |
Now we could use this factory to hire some workers to work.
1 | WorkerFactory factory = new TeacherFactory(); |
Abstract Factory Pattern
This pattern is the most complex one and it violate the open-close principle. So be more careful when using this pattern.
Abstract Factory pattern would be used when we need to create more than one object and use them to work together for one feature. What’s more important is that this part should be stable and won’t change many often. That’s the key point.
Now we have two supermarkets where we could get drink and food. We want to use abstract factory to implement this.
1 | public interface DrinkProvider{ |
Now we use abstract factory pattern to create two supermarket where we could get food and drink of different kinds.
1 | public interface SuperMarket { |
Then we could use factories like this.
1 | SuperMarket shop = new Walmart(); |